package socket1;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 客户端
 */
public class Client {
    private Socket socket;

    public Client(){
        try {
            System.out.println("正在连接服务器：");
            socket =new Socket("localhost",8088);
            System.out.println("服务器连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public  void start(){
        try {
            Scanner scanner=new Scanner(System.in);
            System.out.println("请输入昵称：");
            String nickname=scanner.nextLine().trim();
            while (nickname.isEmpty()){
                System.out.println("昵称不合法，请重新输入");
                nickname=scanner.nextLine().trim();
            }


            OutputStream os=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bw,true);
            //发送昵称,第一次方式的为昵称
            pw.println(nickname);


            //启动线程,用于接收服务器端发送过来的消息
            Thread t1=new Thread(new ServerHandler());
            t1.setDaemon(true);
            t1.start();


            while (true){
                String str=scanner.nextLine();
                if ("exit".equalsIgnoreCase(str)){
                    break;
                }
                pw.println(str);//发送消息
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client=new Client();
        client.start();

    }

    private class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                InputStream in=socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br=new BufferedReader(isr);

                String line;
                //循环读取
                while ((line=br.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
